package com.synjones.idcardusb_reader;

import android.content.Context;
import android.util.Log;

import com.synjones.AppExecutors;
import com.synjones.cominterface.otg.UsbInterfaceAdapter;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.idcard.IDcardReader;
import com.synjones.multireaderlib.MultiReader;

public class IdCardHelper {
    private Context context;
    private MultiReader multiReader= MultiReader.getReader();
    private IDcardReader idcardReader = new IDcardReader(multiReader);
    private OnReadIdCard onReadIdCard;
    UsbInterfaceAdapter usbInterfaceAdapter;
    private boolean running = true;

    public interface OnReadIdCard{
        void onReadIdCard(IDCard idCard);
    }


    private Thread idCardThread = new Thread(new Runnable(){

        @Override
        public void run() {
            while (running){
                IDCardReaderRetInfo iDCardInfo = idcardReader.getIDCardInfo(false, true, false);
                if(!iDCardInfo.isRecvError()){
                    IDCard idCard = iDCardInfo.card;
                    if (idCard!=null){
                        if (onReadIdCard!=null) onReadIdCard.onReadIdCard(idCard);
                    }
                }
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    },"idCardThread");

    public IdCardHelper(Context context) {
        this.context = context;
    }

    public void open(OnReadIdCard onReadIdCard){
        this.onReadIdCard = onReadIdCard;
        AppExecutors.ioExecutor.execute(new Runnable() {
            @Override
            public void run() {
                usbInterfaceAdapter =new  UsbInterfaceAdapter(context);
                if (usbInterfaceAdapter.open()){
                    multiReader.setDataTransInterface(usbInterfaceAdapter);
                    idcardReader.open(context);
                    idcardReader.findIDCard();
                    idCardThread.start();
                }else{
                    Log.e("IdCardDevice","can't open Usb");
                }
            }
        });

    }

    public void close(){
        running = false;
        idCardThread.interrupt();
        usbInterfaceAdapter.close();
        idcardReader.close();
        multiReader.closeReader();
    }


}
